using System;
using System.IO;
using System.Windows.Input;
using Newtonsoft.Json;

namespace GameOverlayWPF
{
    /// <summary>
    /// 热键配置类
    /// </summary>
    public class HotkeySettings
    {
        private static HotkeySettings? _instance;
        private static readonly object _lock = new object();
        private static readonly string ConfigFilePath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "GameOverlayWPF",
            "hotkey_settings.json"
        );

        /// <summary>
        /// 获取单例实例
        /// </summary>
        public static HotkeySettings Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = Load();
                        }
                    }
                }
                return _instance;
            }
        }

        /// <summary>
        /// 显示/隐藏窗口的修饰键（Ctrl, Alt, Shift, Win）
        /// </summary>
        public ModifierKeys Modifiers { get; set; } = ModifierKeys.Control;

        /// <summary>
        /// 显示/隐藏窗口的主键（如 F8）
        /// </summary>
        public Key MainKey { get; set; } = Key.F8;

        /// <summary>
        /// 播放音频的修饰键
        /// </summary>
        public ModifierKeys AudioModifiers { get; set; } = ModifierKeys.Control;

        /// <summary>
        /// 播放音频的主键（如 F9）
        /// </summary>
        public Key AudioMainKey { get; set; } = Key.F9;

        /// <summary>
        /// 窗口透明度（0.3-1.0）
        /// </summary>
        public double WindowOpacity { get; set; } = 0.95;

        /// <summary>
        /// 显示/隐藏窗口热键显示文本
        /// </summary>
        [JsonIgnore]
        public string HotkeyText
        {
            get
            {
                var text = "";
                if (Modifiers.HasFlag(ModifierKeys.Control))
                    text += "Ctrl+";
                if (Modifiers.HasFlag(ModifierKeys.Alt))
                    text += "Alt+";
                if (Modifiers.HasFlag(ModifierKeys.Shift))
                    text += "Shift+";
                if (Modifiers.HasFlag(ModifierKeys.Windows))
                    text += "Win+";
                text += MainKey.ToString();
                return text;
            }
        }

        /// <summary>
        /// 播放音频热键显示文本
        /// </summary>
        [JsonIgnore]
        public string AudioHotkeyText
        {
            get
            {
                var text = "";
                if (AudioModifiers.HasFlag(ModifierKeys.Control))
                    text += "Ctrl+";
                if (AudioModifiers.HasFlag(ModifierKeys.Alt))
                    text += "Alt+";
                if (AudioModifiers.HasFlag(ModifierKeys.Shift))
                    text += "Shift+";
                if (AudioModifiers.HasFlag(ModifierKeys.Windows))
                    text += "Win+";
                text += AudioMainKey.ToString();
                return text;
            }
        }

        /// <summary>
        /// 获取 Windows API 修饰键标志
        /// </summary>
        [JsonIgnore]
        public uint WinModifiers
        {
            get
            {
                uint mod = 0;
                if (Modifiers.HasFlag(ModifierKeys.Control))
                    mod |= 0x0002; // MOD_CONTROL
                if (Modifiers.HasFlag(ModifierKeys.Alt))
                    mod |= 0x0001; // MOD_ALT
                if (Modifiers.HasFlag(ModifierKeys.Shift))
                    mod |= 0x0004; // MOD_SHIFT
                if (Modifiers.HasFlag(ModifierKeys.Windows))
                    mod |= 0x0008; // MOD_WIN
                return mod;
            }
        }

        /// <summary>
        /// 获取显示/隐藏窗口热键的虚拟键码
        /// </summary>
        [JsonIgnore]
        public uint VirtualKeyCode
        {
            get
            {
                return (uint)KeyInterop.VirtualKeyFromKey(MainKey);
            }
        }

        /// <summary>
        /// 获取音频热键的 Windows API 修饰键标志
        /// </summary>
        [JsonIgnore]
        public uint AudioWinModifiers
        {
            get
            {
                uint mod = 0;
                if (AudioModifiers.HasFlag(ModifierKeys.Control))
                    mod |= 0x0002; // MOD_CONTROL
                if (AudioModifiers.HasFlag(ModifierKeys.Alt))
                    mod |= 0x0001; // MOD_ALT
                if (AudioModifiers.HasFlag(ModifierKeys.Shift))
                    mod |= 0x0004; // MOD_SHIFT
                if (AudioModifiers.HasFlag(ModifierKeys.Windows))
                    mod |= 0x0008; // MOD_WIN
                return mod;
            }
        }

        /// <summary>
        /// 获取音频热键的虚拟键码
        /// </summary>
        [JsonIgnore]
        public uint AudioVirtualKeyCode
        {
            get
            {
                return (uint)KeyInterop.VirtualKeyFromKey(AudioMainKey);
            }
        }

        /// <summary>
        /// 从文件加载设置
        /// </summary>
        private static HotkeySettings Load()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"[HotkeySettings] 配置文件路径: {ConfigFilePath}");
                
                if (File.Exists(ConfigFilePath))
                {
                    var json = File.ReadAllText(ConfigFilePath);
                    System.Diagnostics.Debug.WriteLine($"[HotkeySettings] 配置文件内容: {json}");
                    
                    var settings = JsonConvert.DeserializeObject<HotkeySettings>(json);
                    if (settings != null)
                    {
                        System.Diagnostics.Debug.WriteLine($"[HotkeySettings] 已加载 - 热键: {settings.HotkeyText}, 透明度: {settings.WindowOpacity}");
                        return settings;
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"[HotkeySettings] 配置文件不存在");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[HotkeySettings] 加载失败: {ex.Message}");
            }

            // 返回默认设置
            var defaultSettings = new HotkeySettings();
            System.Diagnostics.Debug.WriteLine($"[HotkeySettings] 使用默认设置 - 热键: {defaultSettings.HotkeyText}, 透明度: {defaultSettings.WindowOpacity}");
            return defaultSettings;
        }

        /// <summary>
        /// 保存设置到文件
        /// </summary>
        public void Save()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"[HotkeySettings] 开始保存 - 热键: {HotkeyText}, 透明度: {WindowOpacity}");
                
                // 确保目录存在
                var directory = Path.GetDirectoryName(ConfigFilePath);
                if (directory != null && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                    System.Diagnostics.Debug.WriteLine($"[HotkeySettings] 创建目录: {directory}");
                }

                // 序列化并保存
                var json = JsonConvert.SerializeObject(this, Formatting.Indented);
                System.Diagnostics.Debug.WriteLine($"[HotkeySettings] JSON内容: {json}");
                
                File.WriteAllText(ConfigFilePath, json);
                System.Diagnostics.Debug.WriteLine($"[HotkeySettings] 保存成功到: {ConfigFilePath}");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[HotkeySettings] 保存失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 验证热键是否有效
        /// </summary>
        public bool IsValid()
        {
            // 必须有主键
            if (MainKey == Key.None)
                return false;

            // 主键不能是修饰键本身
            if (MainKey == Key.LeftCtrl || MainKey == Key.RightCtrl ||
                MainKey == Key.LeftAlt || MainKey == Key.RightAlt ||
                MainKey == Key.LeftShift || MainKey == Key.RightShift ||
                MainKey == Key.LWin || MainKey == Key.RWin)
                return false;

            // 检查一些不建议使用的单个按键
            if (Modifiers == ModifierKeys.None)
            {
                // 不允许使用常用的系统按键和字母数字键（容易误触）
                if (MainKey == Key.Escape || MainKey == Key.Tab || MainKey == Key.Enter ||
                    MainKey == Key.Space || MainKey == Key.Back || MainKey == Key.Delete ||
                    MainKey == Key.Home || MainKey == Key.End || MainKey == Key.PageUp || MainKey == Key.PageDown ||
                    MainKey == Key.Up || MainKey == Key.Down || MainKey == Key.Left || MainKey == Key.Right ||
                    MainKey == Key.PrintScreen || MainKey == Key.Pause ||
                    // 字母键
                    (MainKey >= Key.A && MainKey <= Key.Z) ||
                    // 数字键
                    (MainKey >= Key.D0 && MainKey <= Key.D9) ||
                    // 小键盘数字键
                    (MainKey >= Key.NumPad0 && MainKey <= Key.NumPad9))
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 检查是否是保留的系统热键
        /// </summary>
        public bool IsSystemHotkey()
        {
            // 一些常见的系统热键组合
            if (Modifiers == ModifierKeys.Alt && MainKey == Key.F4)
                return true; // Alt+F4 (关闭窗口)
            if (Modifiers == ModifierKeys.Control && MainKey == Key.Escape)
                return true; // Ctrl+Esc (开始菜单)
            if (Modifiers == (ModifierKeys.Control | ModifierKeys.Alt) && MainKey == Key.Delete)
                return true; // Ctrl+Alt+Del
            if (Modifiers == ModifierKeys.Windows && MainKey == Key.L)
                return true; // Win+L (锁定)

            return false;
        }
    }
}
